package com.woniu.woniu_bx.controller;

import com.woniu.woniu_bx.exception.ManagerExistsException;
import com.woniu.woniu_bx.pojo.Manager;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @Description 管理员登录
 * @Author zhangjin
 * @Date 2022/8/29 11:05
 */
@RestController
@RequestMapping("/admin")
public class AdminLoginController {
    @Autowired
    private ManagerService managerService;

    @RequestMapping("/login")
    public ResponseEntity doLogin(@RequestBody Manager manager){
        Manager admin = managerService.getManagerByAccount(manager.getAccount());
        if (admin==null){
            throw new ManagerExistsException("账户不存在");
        }else{
            return ResponseEntity.SUCCESS("操作成功",admin);
        }
    }
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('admin:add')")
    public ResponseEntity addAdminUser(@RequestBody @Valid Manager manager){
        Manager admin = managerService.getManagerByAccount(manager.getAccount());
        if (admin!=null){
            throw new ManagerExistsException("账户已存在");
        }else{
            //设置状态
            manager.setStatus("y");
            managerService.addManager(manager);
            return ResponseEntity.SUCCESS("添加成功",null);
        }
    }
    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('admin:update')")
    public ResponseEntity updateAdmin(@RequestBody Manager manager){
        if (manager.getId()==null){
            throw new ManagerExistsException("账户id无效");
        }else{
            managerService.updateManager(manager);
            return ResponseEntity.SUCCESS("操作成功",null);
        }
    }
}
